/**
 * Copyright (C) 2013 DaiKit.com - daikit4gxt-sample module (admin@daikit.com)
 *
 *         Project home : http://code.daikit.com/commons
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.daikit.daikit4gxtsample.client.ui;

import com.daikit.daikit4gxtsample.client.Main;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.core.client.util.Util;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.widget.core.client.grid.GridView;


/**
 * Wrapper to {@link GridView} permitting to provide custom to string
 * 
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 * @param <M>
 *           the displayed model type
 */
public class DrtGridView<M> extends GridView<M>
{

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sencha.gxt.widget.core.client.grid.GridView#getRenderedValue(int, int, java.lang.Object,
	 * com.sencha.gxt.data.shared.Store.Record)
	 */
	@Override
	protected <N> SafeHtml getRenderedValue(final int rowIndex, final int colIndex, final M m, final ListStore<M>.Record record)
	{
		final ValueProvider<? super M, N> valueProvider = cm.getValueProvider(colIndex);
		N val = null;
		if (record != null)
		{
			val = record.getValue(valueProvider);
		}
		else
		{
			val = valueProvider.getValue(m);
		}
		final Cell<N> r = cm.getCell(colIndex);
		if (r != null)
		{
			final SafeHtmlBuilder sb = new SafeHtmlBuilder();
			r.render(new Context(rowIndex, colIndex, ds.getKeyProvider().getKey(m)), val, sb);
			return sb.toSafeHtml();
		}

		String text = null;
		if (val != null)
		{
			text = renderNotNullValue(val);
		}
		return Util.isEmptyString(text) ? SafeHtmlUtils.fromTrustedString("&#160;") : SafeHtmlUtils.fromString(text);
	}

	protected <N> String renderNotNullValue(final N value)
	{
		String ret;
		if (value instanceof Boolean)
		{
			ret = ((Boolean) value).booleanValue() ? Main.i18n().label_true() : Main.i18n().label_false();
		}
		else
		{
			ret = value.toString();
		}
		return ret;
	}

}
